import { useState } from "react";
import { useForm } from "react-hook-form";
import { zodResolver } from "@hookform/resolvers/zod";
import { useTranslation } from "react-i18next";
import {
  Dialog,
  DialogContent,
  DialogDescription,
  DialogHeader,
  DialogTitle,
} from "@/components/ui/dialog";
import {
  Form,
  FormControl,
  FormField,
  FormItem,
  FormLabel,
  FormMessage,
} from "@/components/ui/form";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { UpdateEmailSchema, type UpdateEmailFormData } from "@/schemas/update-email";
import { useSendEmailUpdateCaptcha, useUpdateEmail } from "@/hooks/use-update-email";
import { Mail, Send } from "lucide-react";

interface UpdateEmailDialogProps {
  open: boolean;
  onOpenChange: (open: boolean) => void;
  currentEmail?: string;
}

export function UpdateEmailDialog({
  open,
  onOpenChange,
}: UpdateEmailDialogProps) {
  const { t } = useTranslation();
  const [isCaptchaSent, setIsCaptchaSent] = useState(false);
  
  const { sendEmailUpdateCaptcha, isSendingCaptcha } = useSendEmailUpdateCaptcha();
  const { updateEmail, isUpdatingEmail } = useUpdateEmail();

  const form = useForm<UpdateEmailFormData>({
    resolver: zodResolver(UpdateEmailSchema()),
    defaultValues: {
      email: "",
      captcha: "",
    },
  });

  const handleSendCaptcha = async () => {
    const email = form.getValues("email");
    
    if (!email) {
      form.setError("email", {
        type: "manual",
        message: t("Email is required", { defaultValue: "Email is required" }),
      });
      return;
    }

    try {
      await sendEmailUpdateCaptcha(email);
      setIsCaptchaSent(true);
    } catch {
      // 错误处理已经在 hook 中处理
    }
  };

  const onSubmit = async (data: UpdateEmailFormData) => {
    try {
      await updateEmail(data, {
        onSuccess: () => {
          onOpenChange(false);
          form.reset();
          setIsCaptchaSent(false);
        },
      });
    } catch {
      // 错误处理已经在 hook 中处理
    }
  };

  const handleOpenChange = (newOpen: boolean) => {
    if (!newOpen) {
      form.reset();
      setIsCaptchaSent(false);
    }
    onOpenChange(newOpen);
  };

  return (
    <Dialog open={open} onOpenChange={handleOpenChange}>
      <DialogContent className="sm:max-w-[425px]">
        <DialogHeader>
          <DialogTitle className="flex items-center gap-2">
            <Mail className="w-5 h-5" />
            {t("Update Email", { defaultValue: "Update Email" })}
          </DialogTitle>
          <DialogDescription>
            {t("Update your email address. A verification code will be sent to your new email.", {
              defaultValue: "Update your email address. A verification code will be sent to your new email.",
            })}
          </DialogDescription>
        </DialogHeader>

        <Form {...form}>
          <form onSubmit={form.handleSubmit(onSubmit)} className="space-y-4">
            <FormField
              control={form.control}
              name="email"
              render={({ field }) => (
                <FormItem>
                  <FormLabel>
                    {t("New Email", { defaultValue: "New Email" })}
                  </FormLabel>
                  <div className="flex gap-2">
                    <FormControl>
                      <Input
                        placeholder={t("Enter new email", {
                          defaultValue: "Enter new email",
                        })}
                        {...field}
                        disabled={isCaptchaSent}
                      />
                    </FormControl>
                    <Button
                      type="button"
                      variant="outline"
                      onClick={handleSendCaptcha}
                      disabled={isSendingCaptcha || isCaptchaSent || !form.watch("email")}
                      className="whitespace-nowrap"
                    >
                      <Send className="w-4 h-4 mr-1" />
                      {isSendingCaptcha
                        ? t("Sending...", { defaultValue: "Sending..." })
                        : t("Send Code", { defaultValue: "Send Code" })}
                    </Button>
                  </div>
                  <FormMessage />
                </FormItem>
              )}
            />

            {isCaptchaSent && (
              <FormField
                control={form.control}
                name="captcha"
                render={({ field }) => (
                  <FormItem>
                    <FormLabel>
                      {t("Verification Code", { defaultValue: "Verification Code" })}
                    </FormLabel>
                    <FormControl>
                      <Input
                        placeholder={t("Enter verification code", {
                          defaultValue: "Enter verification code",
                        })}
                        {...field}
                      />
                    </FormControl>
                    <FormMessage />
                  </FormItem>
                )}
              />
            )}

            <div className="flex justify-end gap-2 pt-4">
              <Button
                type="button"
                variant="outline"
                onClick={() => handleOpenChange(false)}
                disabled={isUpdatingEmail}
              >
                {t("Cancel", { defaultValue: "Cancel" })}
              </Button>
              <Button
                type="submit"
                disabled={isUpdatingEmail || !isCaptchaSent}
              >
                {isUpdatingEmail
                  ? t("Updating...", { defaultValue: "Updating..." })
                  : t("Update Email", { defaultValue: "Update Email" })}
              </Button>
            </div>
          </form>
        </Form>
      </DialogContent>
    </Dialog>
  );
}
